package com.yimi.yinhepda.views.unload_module.UnBlocking;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;

import com.pda.ym.utils.DateHelper;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.ScanBlockingAdapter;
import com.yimi.yinhepda.adapter.SpinnerAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.db.dao.LineVoTableDao;
import com.yimi.yinhepda.db.table.LineVoTable;
import com.yimi.yinhepda.entity.bean.SealNoEntity;
import com.yimi.yinhepda.entity.bean.SealOrUnsealTaskEntity;
import com.yimi.yinhepda.entity.request.ArriveUnloadTheCarEntity;
import com.yimi.yinhepda.entity.request.SealManagerRequest;
import com.pda.ym.entity.bean.ImageInfo;
import com.pda.ym.entity.bean.ImageInfoResponse;
import com.yimi.yinhepda.entity.response.QueryPhotographDictResponse;
import com.yimi.yinhepda.entity.response.SealDownloadResponse;
import com.yimi.yinhepda.entity.response.SuccessResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.ActivityStack;
import com.yimi.yinhepda.event.CreateStowagesEvent;
import com.yimi.yinhepda.utils.BitmapUtils;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.EditTextDialog;
import com.pda.uce.commom.util.MyDialog;
import com.yimi.yinhepda.utils.PermissionUtils;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.SelectPicView;
import com.pda.ym.utils.SoundVibratorManager;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by xionggaosheng on 2018/6/5.
 * 解封扫描封签界面
 */

public class ScanBlockingActivity extends BaseActivity implements AdapterView.OnItemSelectedListener {

    /**
     * 相机权限
     */
    private final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA};
    /**
     * 权限请求值
     */
    private final int REQUEST_CODE_PERMISSIONS = 100;
    /**
     * 破损类型选项
     */
    private Spinner spBlockingType;
    /**
     * 破损类型适配器
     */
    private SpinnerAdapter<String> spinnerAdapter;
    /**
     * 破损类型列表
     */
    private List<String> blockingTypeList = new ArrayList<>();
    /**
     * 图片
     */
    private LinearLayout llCamera;
    /**
     * 封签号列表
     */
    private RecyclerView rvTaskNo;
    /**
     * 图片展示控件
     */
    private SelectPicView selectPicView;
    /**
     * 封签号列表适配器
     */
    private ScanBlockingAdapter scanBlockingAdapter;
    /**
     * 返回按钮
     */
    private Button ibBack;
    /**
     * 数据
     */
    private List<SealNoEntity> dataList = new ArrayList<>();
    /**
     * 下载封签号集合
     */
    private List<String> sealsNoList = new ArrayList<>();
    /**
     * 扫描封签号集合
     */
    private List<String> scanSealsNoList = new ArrayList<>();
    /**
     * 选择封签类型 0.无异常  1.封签遗失  2.封签破损
     */
    private int selectBrokenType;
    /**
     * 解封按钮
     */
    private Button btnUnBlocking;
    /**
     * 添加按钮
     */
    private ImageButton ibAdd;
    /**
     * 配载单号
     */
    private String stowageNo;
    /**
     * 运输方式：1-trunk_line干线,2-branch_line支线,3-car_load:整车
     */
    private int bizType;
    /**
     * 任务号
     */
    private String taskNo;
    /**
     * 页面跳转码
     */
    public static final int RESULT_OK_201 = 201;
    /**
     * 解封标签类
     */
    private SealOrUnsealTaskEntity mEntity;
    /**
     * 解封上传图片Key
     */
    private String mImageId = "";

    public ScanBlockingActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_blocking);
        selectPicView = findViewById(R.id.ll_img);
        spBlockingType = findViewById(R.id.sp_blocking_type);
        llCamera = findViewById(R.id.ll_camera);
        rvTaskNo = findViewById(R.id.lv_task_no);
        ibBack = findViewById(R.id.btn_back);
        btnUnBlocking = findViewById(R.id.btn_un_blocking);
        ibAdd = findViewById(R.id.ib_plus);

        blockingTypeList.addAll(Arrays.asList(getResources().getStringArray(R.array.unblocking_type)));
        spinnerAdapter = new SpinnerAdapter<String>(this, R.layout.simple_spinner_item, blockingTypeList);
        spBlockingType.setAdapter(spinnerAdapter);
        spBlockingType.setOnItemSelectedListener(this);

        //        dataList.add(new StockInLocalDeptChildWaybillEntity());
        scanBlockingAdapter = new ScanBlockingAdapter(this, dataList);
        rvTaskNo.setLayoutManager(new LinearLayoutManager(this));
        rvTaskNo.setAdapter(scanBlockingAdapter);

        llCamera.setOnClickListener(this);
        ibBack.setOnClickListener(this);
        ibAdd.setOnClickListener(this);
        btnUnBlocking.setOnClickListener(this);

        mEntity = (SealOrUnsealTaskEntity) getIntent().getSerializableExtra("task");
        stowageNo = mEntity.getTaskNo();
        if (mEntity.getBeTask() == 1) {
            //车线任务
            LineVoTable lineTable = new LineVoTableDao().findLine(mEntity.getNextDeptCode(), sharedPreferUtil.getDeptCode());
            if (lineTable != null) {
                bizType = Integer.parseInt(lineTable.getTransportWay());
            }
        } else {
            //支线
            bizType = 2;
        }

        taskNo = mEntity.getTaskNo();

        downloadSeals();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_camera:
                checkPersmisson();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_un_blocking:
//                uploadImage();
                queryDictValue();
                break;
            case R.id.ib_plus:
                showAddDialog();
                break;
            default:
                break;
        }
    }

    /**
     * 查询数据字典：强制封签拍照
     */
    private void queryDictValue() {
        showPgDlg("数据请求中...");
        Map<String, String> params = new HashMap<>();
        params.put("params", "coerce_photograph");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_DICT_VALUE)
                .setParams(params)
                .setResponsClazz(QueryPhotographDictResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryPhotographDictResponse response = (QueryPhotographDictResponse) obj;
                        boolean hasDeptCode = false;
                        if (response.getData() != null) {
                            Map<String, String> maps = response.getData().getCoercePhotograph();
                            for (String key : maps.keySet()) {
                                String value = maps.get(key);
                                String deptCode = sharedPreferUtil.getDeptCode();
                                if (deptCode.equals(value)) {
                                    hasDeptCode = true;
                                    break;
                                }
                            }
                        }
                        if (hasDeptCode) {
                            List<String> pickPic = selectPicView.getPickPic();
                            if (pickPic == null || pickPic.isEmpty()) {
                                showToast("当前部门需添加照片上传");
                                return;
                            }
                        }
                        //上传照片后，上传解封数据，在跳转到解封卸车界面
                        uploadImage();
                    }
                });
    }

    private void checkPersmisson() {
        PermissionUtils.checkMorePermissions(this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                selectPicView.takePhotoFunction(ScanBlockingActivity.this);
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                PermissionUtils.requestMorePermissions(ScanBlockingActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(ScanBlockingActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSIONS:
                PermissionUtils.onRequestMorePermissionsResult(ScanBlockingActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                        selectPicView.takePhotoFunction(ScanBlockingActivity.this);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        PermissionUtils.requestMorePermissions(ScanBlockingActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        Common.showPermissionDialog(ScanBlockingActivity.this, "程序需要获取相机权限，才能继续使用，请去权限界面打开！", null);
                    }
                });
                break;
            default:
                break;
        }
    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        selectBrokenType = i;
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 下载封签号
     */
    public void downloadSeals() {

        if (stowageNo != null) {
            if (stowageNo.startsWith("J")) {
                //壹米快运配载单号
                stowageNo = stowageNo.toUpperCase();
                if (!StringUtils.isCarCodeNo(stowageNo)) {
                    showToast("输入正确的配载单号!");
                    return;
                }
            }

            showPgDlg("正在加载...");

            SealManagerRequest request = new SealManagerRequest();
            request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
            request.setTaskNo(stowageNo);

            NetRequest netRequest = new NetRequest();
            netRequest.setMethod(NetRequest.Method.POST_STRING);
            netRequest.setUrl(Constants.URL_V2_QUERY_SEAL_INFO);
            netRequest.setRequestObject(request);
            netRequest.setResponsClazz(SealDownloadResponse.class);
            netRequest.execute(new UICallBack() {
                @Override
                public void onError(String msg) {
                    if (msg != null) {
                        showToast(msg);
                    } else {
                        showToast("服务器出错了!");
                    }
                    SoundVibratorManager.playSound(2);
                    dismissPgDlg();
                }

                @Override
                public void onSuccess(Object obj) {
                    dismissPgDlg();
                    SealDownloadResponse response = (SealDownloadResponse) obj;
                    if (response == null || response.getData() == null) {
                        SoundVibratorManager.playSound(2);
                        if (response.getErrorMessages() != null && response.getErrorMessages().length > 0) {
                            showToast(response.getErrorMessages()[0]);
                            SoundVibratorManager.playSound(2);
                        } else {
                            showToast("封签数据下载失败!");
                            SoundVibratorManager.playSound(2);
                        }
                        return;
                    }
                    sealsNoList.clear();
                    if (response.getData() != null && response.getData().getSealNos() != null) {
                        sealsNoList.addAll(response.getData().getSealNos());
                    }
                }
            });
        }
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("封签号扫描失败");
        } else if (!StringUtils.isSealsNO(result)) {
            showToast("封签号格式不正确！");
        } else {
            SoundVibratorManager.playSound(1);
            if (!scanSealsNoList.contains(result)) {
                scanSealsNoList.add(result);
                dataList.add(new SealNoEntity(result));
                scanBlockingAdapter.notifyDataSetChanged();
            }
        }
    }

    private int getExceptionType() {
        if (selectBrokenType != 0) {
            return selectBrokenType + 1;
        }

//    if (sealsNoList.size() > 0) {
//      for (String seals : sealsNoList) {
//        boolean hasElement = false;
//        for (String scanSeals : scanSealsNoList) {
//          if (seals.equals(scanSeals)) {
//            hasElement = true;
//            break;
//          }
//        }
//
//        if (!hasElement) {
//          //遍历完无该元素，则没有全部扫描 则封签号漏扫
//          return 4;
//        }
//      }
//    }
//
//    for (String scanSeal : scanSealsNoList) {
//      if (!sealsNoList.contains(scanSeal)) {
//        //如果扫描的元素，原集合不存在 则封签号错误
//        return 5;
//      }
//    }

        if (scanSealsNoList.size() <= 0) {
            if (sealsNoList.size() == 0) {
                return 1;
            }
            //解封漏扫
            return 4;
        } else {
            for (String scanSeals : scanSealsNoList) {
                boolean hasElement = false;
                for (String seals : sealsNoList) {
                    if (seals.equals(scanSeals)) {
                        hasElement = true;
                        break;
                    }
                }
                if (!hasElement) {
                    //遍历完无该元素，则没有全部扫描 则封签号错误
                    return 5;
                }
            }
        }
        //返回 正常解封类型
        return 1;
    }

    /**
     * 图片上传
     */
    private void uploadImage() {
        final List<String> pickPic = selectPicView.getPickPic();
        int PICURE_NUM = 6;
        if (pickPic != null && pickPic.size() > 0) {
            if (pickPic.size() > PICURE_NUM) {
                showToast("图片不可大于" + PICURE_NUM + "张！");
                return;
            }
            showPgDlg("正在上传图片数据...");
            final Map param = new HashMap();
            //4为图片上传格式规范ID，8为视频上传规范ID
            param.put("uploaderStrategyId", "4");

            final NetRequest request = new NetRequest();
            Observable.create(new Observable.OnSubscribe<Void>() {
                @Override
                public void call(Subscriber<? super Void> subscriber) {
                    for (int i = 0; i < pickPic.size(); i++) {
                        String item = pickPic.get(i);

                        Bitmap mBitmap = BitmapUtils.decodeSampledBitmapFromFile(item, 800, 1100);
                        BitmapUtils.compressBmpToFile(mBitmap, item);

                        String fileName = item.substring(item.lastIndexOf("/") + 1);
                        request.addFile("file" + i, fileName, new File(item));
                    }
                    subscriber.onCompleted();
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
                @Override
                public void onCompleted() {
                    request.setParams(param)
                            .setMethod(NetRequest.Method.POST)
                            .setUrl(Constants.URL_UPLOAD_IMAGE)
                            .setResponsClazz(ImageInfoResponse.class)
                            .execute(new UICallBack() {
                                @Override
                                public void onError(String msg) {
                                    setScannerEnabled(true);
                                    dismissPgDlg();
                                    SoundVibratorManager.playSound(2);
                                    if (msg != null) {
                                        showToast("图片上传失败:" + msg);
                                    } else {
                                        showToast("图片上传失败!");
                                    }
                                }

                                @Override
                                public void onSuccess(Object obj) {
                                    setScannerEnabled(true);
                                    dismissPgDlg();
                                    SoundVibratorManager.playSound(1);
                                    ImageInfoResponse response = (ImageInfoResponse) obj;
                                    mImageId = "";
                                    for (ImageInfo item : response.getData()) {
                                        mImageId += (item.getFileKey() + ",");
                                    }
                                    mImageId = mImageId.substring(0, mImageId.length() - 1);
                                    //检查解封数据
                                    checkData();
                                }
                            });
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onNext(Void aVoid) {
                }
            });
        } else {
            //检查解封数据
            checkData();
        }
    }

    /**
     * 提示需拍照
     */
    private void showNoPhtotDialog() {
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("提示");
        dialog.setMessage("至少两张封车照片上传，请先拍照");
        dialog.setPositiveClickListener("拍照",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        selectPicView.openPhotoFunction(ScanBlockingActivity.this);
                    }
                });
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void checkData() {

        if (stowageNo.startsWith("J")) {
            //快递配载单,干线至少一条封签码
            if (bizType == 1 && (scanSealsNoList == null || scanSealsNoList.isEmpty())) {
                //干线，没有封签则提示
                MyDialog dialog = new MyDialog(this);
                dialog.setIcon(R.drawable.alert);
                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                dialog.setMessage("当前任务运输方式为干线且为快递所有，需要至少一条解封签码！");
                dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            } else {
                update();
            }
        } else {
            //快运配载单
            if (getExceptionType() == 2 || getExceptionType() == 3) {
                if (selectPicView.getPickPic().isEmpty()) {
                    showToast("封签异常请选择图片");
                    return;
                }
            }
            if (bizType == 1 && (getExceptionType() == 2 || getExceptionType() == 3)) {
                if (selectPicView.getPickPic().size() < (sealsNoList.size() - scanSealsNoList.size())) {
                    showToast("封签丢失/破损" + (sealsNoList.size() - scanSealsNoList.size()) + "条，请上传" +
                            (sealsNoList.size() - scanSealsNoList.size()) + "张照片");
                    return;
                }
            }

            if (getExceptionType() == 4 || getExceptionType() == 5) {
                MyDialog dialog = new MyDialog(this);
                dialog.setIcon(R.drawable.alert);
                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                dialog.setTitle("提示");
                dialog.setMessage(getExceptionType() == 4 ? "当前存在解封漏扫行为，是否强制提交？" : "当前存在解封错误行为，是否强制提交？");
                dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //解封数据
                        update();
                        dialog.dismiss();
                    }
                });
                dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            } else {
                update();
            }
        }
    }

    public void update() {

        ArriveUnloadTheCarEntity entity = new ArriveUnloadTheCarEntity();
        entity.setTaskNo(taskNo);
        entity.setDestDeptCode(sharedPreferUtil.getDeptCode());
        entity.setBeTask(mEntity.getBeTask());
        entity.setSealModel(getExceptionType());
        entity.setSealNos(scanSealsNoList);
        entity.setOperateTime(DateHelper.getDateTimeFormate(new Date()));
        entity.setFileIds(mImageId);
        entity.setBizTypeCode(bizType);

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_V2_END_SEALING_CAR)
                .setRequestObject(entity)
                .setResponsClazz(SuccessResponse.class)
                .setConnTimeOut(10 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("服务器出错了!");
                        }
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        SuccessResponse response = (SuccessResponse) obj;
                        if (response.isSuccess()) {
                            selectPicView.setClearPic();
                            scanSealsNoList.clear();
                            scanBlockingAdapter.notifyDataSetChanged();
                            finishUnSealDialog();
                        }
                    }
                });
    }

    /**
     * 解封完成提示界面跳转
     */
    private void finishUnSealDialog() {
        if (this.isFinishing()) {
            return;
        }
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setTitle("提示");
        dialog.setMessage("解封完成，是否进入解封卸车界面？");
        dialog.setPositiveClickListener(Constants.confirmMsg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(ScanBlockingActivity.this, BlockingUnloadTaskActivity.class);
                intent.putExtra("task", mEntity);
                startActivity(intent);
                finish();
                for (BaseActivity activity : ActivityStack.getInstance().getActivities()) {
                    if (activity instanceof UnBlockingActivity) {
                        activity.finish();
                    }
                }
            }
        });
        dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
                CreateStowagesEvent event = new CreateStowagesEvent();
                event.setFromActivity(5);
                EventBus.getDefault().post(event);
            }
        });
        dialog.show();
    }

    private void showAddDialog() {
        final EditTextDialog exitDialog = new EditTextDialog(this);
        exitDialog.setPositiveClickListener(R.drawable.btn_bg_ok_common, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                String num = exitDialog.getmExitPwd().getText().toString().trim();

                if ("".equals(num)) {
                    showToast("未输入封签号码");
                } else if (!StringUtils.isSealsNO(num)) {
                    showToast("非封签号码，请输入数字8位到10位");
                } else {
                    if (!scanSealsNoList.contains(num)) {
                        scanSealsNoList.add(num);
                        dataList.add(new SealNoEntity(num));
                        scanBlockingAdapter.notifyDataSetChanged();
                    }
                    exitDialog.dismiss();
                }
            }
        });
        exitDialog.setCanceledOnTouchOutside(false);
        exitDialog.setCancelable(false);
        exitDialog.show();
    }

    @Override
    public String getPageName() {
        return "封签扫描";
    }
}
